package org.jeecg.modules.demo.projectmanagement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.basejobserve.service.IBaseJobServeService;
import org.jeecg.modules.demo.basejobserveitem.entity.BaseJobServeItem;
import org.jeecg.modules.demo.basejobserveitem.service.IBaseJobServeItemService;
import org.jeecg.modules.demo.basejobshop.entity.BaseJobShop;
import org.jeecg.modules.demo.basejobshop.service.IBaseJobShopService;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectInfo;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectManagement;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.dmyweb.base.service.IBaseService;
import org.jeecg.modules.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description:
 * @Author: jeecg-boot
 * @Date: 2021-12-31
 * @Version: V1.0
 */
@Api(tags = "项目管理")
@RestController
@RequestMapping("/projectmanagement/projectManagement")
@Slf4j
public class ProjectManagementController extends JeecgController<ProjectManagement, IProjectManagementService> {
    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IBaseService baseService;
    @Autowired
    private IBaseJobServeService baseJobServeService;
    @Autowired
    private IBaseJobShopService baseJobShopService;
    @Autowired
    private IBaseJobServeItemService baseJobServeItemService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "项目管理-分页列表查询")
    @ApiOperation(value = "项目管理-分页列表查询", notes = "项目管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ProjectManagement projectManagement,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        projectManagementService.updateVolume(storeId);
        QueryWrapper<ProjectManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);


        //queryWrapper.eq("is_show", 1);
        // req.getParameterMap()被锁定无法删除元素，复制一份
        Map<String, String[]> pMap = new HashMap<>(req.getParameterMap());
        String[] columns = pMap.get("column");
        String column = columns == null || columns.length == 0 ? null : columns[0];
        if (StringUtils.isEmpty(column) || "createTime".equals(column)) {
            // 没有排序条件时，默认用权重排序
            pMap.put("column", new String[]{"project_weight"});
            pMap.put("order", new String[]{"asc"});
        }
        if (StringUtils.isEmpty(projectManagement.getIsActivate())) {
            projectManagement.setIsActivate("1");
        }
        QueryGenerator.initQueryWrapper(queryWrapper, projectManagement, pMap);
        Page<ProjectManagement> page = new Page<>(pageNo, pageSize);
        IPage<ProjectManagement> pageList = projectManagementService.page(page, queryWrapper);

        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     */
    @AutoLog(value = "项目管理-搜索查询")
    @ApiOperation(value = "项目管理-搜索查询", notes = "项目管理-搜索查询")
    @PostMapping("/search")
    public Result<?> search(@RequestBody Map<String, Object> map, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        map.put("storeId", storeId);

        return Result.OK(projectManagementService.search(map));
    }

    @AutoLog(value = "项目管理-分类查询")
    @ApiOperation(value = "项目管理-分类查询", notes = "项目管理-分类查询")
    @GetMapping(value = "/selfJson")
    public Result<?> selfJson(HttpServletRequest req) {
        //LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        String sql = "SELECT project_group as projectGroup FROM project_management WHERE store_id = '" + storeId + "' GROUP BY project_group";
        List<Map<String, Object>> classifyList = baseService.getSqlQuery(sql);

        JSONObject obj = new JSONObject();
        JSONArray arrays = new JSONArray();
        int index = 0;

        for (Map<String, Object> bean : classifyList) {
            index++;
            String classify = String.valueOf(bean.get("projectGroup"));
            JSONObject projectNames = new JSONObject();
            projectNames.put("id", index);
            projectNames.put("name", classify);
            JSONArray array = new JSONArray();
            if (oConvertUtils.isNotEmpty(classify)) {
                QueryWrapper<ProjectManagement> query = new QueryWrapper<>();
                query.eq("store_id", storeId);
                query.eq("project_group", classify);
                List<ProjectManagement> listData = projectManagementService.list(query);
                for (ProjectManagement commodity : listData) {
                    JSONObject card = new JSONObject();
                    card.put("id", commodity.getId());
                    card.put("name", commodity.getProjectName());
                    card.put("content", commodity.getItemDescription());
                    card.put("url", commodity.getProjectPic());
                    array.add(card);
                }
            }
            projectNames.put("card", array);
            arrays.add(projectNames);
        }
        obj.put("projectNames", arrays);
        return Result.OK(obj);
    }

    @AutoLog(value = "项目管理-获取服务列表")
    @ApiOperation(value = "项目管理-获取服务列表", notes = "项目管理-获取服务列表")
    @GetMapping(value = "/serveList")
    public Result<?> serveList(@RequestParam("projectId") String projectId, HttpServletRequest req) {
        //HttpServletRequest req
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        List<Map<String, Object>> list = projectManagementService.serveList(storeId, projectId);
        if (list != null && list.get(0) == null) {
            list = Collections.emptyList();
        }
        return Result.OK(list);
    }

    @AutoLog(value = "项目管理-获取商品列表")
    @ApiOperation(value = "项目管理-获取商品列表", notes = "项目管理-获取商品列表")
    @GetMapping(value = "/shopList")
    public Result<?> shopList(@RequestParam("projectId") String projectId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        List<Map<String, Object>> list = projectManagementService.shopList(storeId, projectId);
        if (list != null && list.get(0) == null) {
            list = Collections.emptyList();
        }
        return Result.OK(list);
    }

    /**
     * 根据分组id查询项目列表
     */
    @RequestMapping(value = "/getListByGroupId", method = RequestMethod.GET)
    public Result<List<ProjectInfo>> getListByGroupId(
            @RequestParam(name = "pageNo", required = true) Integer pageNo,
            @RequestParam(name = "storeId", required = true) String storeId,
            @RequestParam(name = "groupId", required = true) String groupId) {
        Result<List<ProjectInfo>> result = new Result<>();
        List<ProjectInfo> list = projectManagementService.getListByGroupId(pageNo, 10, storeId, groupId);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    /**
     * 添加
     */
    @AutoLog(value = "项目管理-添加")
    @ApiOperation(value = "项目管理-添加", notes = "项目管理-添加")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> add(@RequestBody JSONObject obj, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }

        JSONObject vo = obj.getJSONObject("projectManagement");
        ProjectManagement projectManagement = JSON.parseObject(vo.toJSONString(), ProjectManagement.class);
        JSONArray jobServe = obj.getJSONArray("jobServe");
        JSONArray jobShop = obj.getJSONArray("jobShop");

        // 当前店铺全部项目
        List<ProjectManagement> list = projectManagementService.list(new QueryWrapper<ProjectManagement>().eq("store_id", storeId));
        // list中与projectManagement同名的项目个数
        long count = list.stream().filter(pm -> pm.getProjectName().equals(projectManagement.getProjectName())).count();
        if (count > 0) {
            return Result.error("添加失败，该店铺已有同名项目！");
        }
        if (projectManagement.getProjectPrice() < 0) {
            return Result.error("添加失败，价格不能小于0！");
        }
        if (projectManagement.getCostPrice() < 0) {
            return Result.error("添加失败，成本价不能小于0！");
        }
        if (projectManagement.getGrossProfit() < 0 || projectManagement.getGrossProfit() > 100) {
            return Result.error("添加失败，毛利率应在0-100范围内！");
        }
        if (projectManagement.getMinimumProfit() < 0 || projectManagement.getMinimumProfit() > 100) {
            return Result.error("添加失败，最低股东分红点应在0-100范围内！");
        }
        projectManagement.setStoreId(storeId);
        projectManagement.setProjectNum(getNewCode(storeId));
        projectManagement.setVolume(0);
        projectManagementService.save(projectManagement);

        for (int i = 0; i < jobServe.size(); i++) {
            JSONObject json = jobServe.getJSONObject(i);
            BaseJobServeItem serve = new BaseJobServeItem();
            serve.setServeNum(json.getInteger("serveNum"));
            serve.setStoreId(storeId);
            serve.setProjectId(projectManagement.getId());
            serve.setServeId(json.getString("id"));
            baseJobServeItemService.save(serve);
        }

        for (int i = 0; i < jobShop.size(); i++) {
            JSONObject json = jobShop.getJSONObject(i);
            BaseJobShop shop = new BaseJobShop();
            shop.setShopId(json.getString("id"));
            shop.setProjectId(projectManagement.getId());
            shop.setShopNum(json.getInteger("shopNum"));
            shop.setStoreId(storeId);
            baseJobShopService.save(shop);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 批量修改分组
     */
    @AutoLog(value = "项目管理-编辑")
    @ApiOperation(value = "项目管理-编辑", notes = "项目管理-编辑")
    @GetMapping(value = "/edits")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> edits(@RequestParam("ids") String ids, @RequestParam("projectGroupId") String projectGroupId, @RequestParam("projectGroupName") String projectGroupName) {
        if (oConvertUtils.isNotEmpty(ids)) {
            String[] listid = ids.split(",");
            for (String id : listid) {
                ProjectManagement projectManagement = new ProjectManagement();
                projectManagement.setId(id);
                projectManagement.setProjectGroup(projectGroupName);
                projectManagement.setGroupId(projectGroupId);
                projectManagementService.updateById(projectManagement);
            }
        }
        return Result.OK("编辑成功！");
    }

    /**
     * 批量上架/下架
     */
    @AutoLog(value = "项目管理-编辑")
    @ApiOperation(value = "项目管理-编辑", notes = "项目管理-编辑")
    @GetMapping(value = "/editAllId")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> editAllId(@RequestParam("ids") String ids, @RequestParam("isActivate") String isActivate) {
        if (oConvertUtils.isNotEmpty(ids)) {
            String[] listid = ids.split(",");
            for (String id : listid) {
                ProjectManagement projectManagement = new ProjectManagement();
                projectManagement.setId(id);
                projectManagement.setIsActivate(isActivate);
                projectManagementService.updateById(projectManagement);
            }
        }
        return Result.OK("编辑成功！");
    }

    /**
     * 编辑
     */
    @AutoLog(value = "项目管理-编辑")
    @ApiOperation(value = "项目管理-编辑", notes = "项目管理-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> edit(@RequestBody JSONObject obj, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }

        JSONObject vo = obj.getJSONObject("projectManagement");
        ProjectManagement projectManagement = JSON.parseObject(vo.toJSONString(), ProjectManagement.class);
        JSONArray jobServe = obj.getJSONArray("jobServe");
        JSONArray jobShop = obj.getJSONArray("jobShop");

        // 当前店铺全部项目（除自己）
        List<ProjectManagement> list = projectManagementService.list(new QueryWrapper<ProjectManagement>()
                .eq("store_id", storeId)
                .ne("id", projectManagement.getId()));
        // list中与projectManagement同名的项目个数
        long count = list.stream().filter(pm -> pm.getProjectName().equals(projectManagement.getProjectName())).count();
        if (count > 0) {
            return Result.error("编辑失败，该店铺已有同名项目！");
        }
        if (projectManagement.getProjectPrice() < 0) {
            return Result.error("编辑失败，价格不能小于0！");
        }
        if (projectManagement.getCostPrice() < 0) {
            return Result.error("编辑失败，成本价不能小于0！");
        }
        if (projectManagement.getGrossProfit() < 0 || projectManagement.getGrossProfit() > 100) {
            return Result.error("编辑失败，毛利率应在0-100范围内！");
        }
        if (projectManagement.getMinimumProfit() < 0 || projectManagement.getMinimumProfit() > 100) {
            return Result.error("编辑失败，最低股东分红点应在0-100范围内！");
        }
        projectManagementService.updateById(projectManagement);

        QueryWrapper<BaseJobServeItem> queryServe = new QueryWrapper<>();
        queryServe.eq("project_id", projectManagement.getId());
        baseJobServeItemService.remove(queryServe);
        for (int i = 0; i < jobServe.size(); i++) {
            JSONObject json = jobServe.getJSONObject(i);
            BaseJobServeItem serve = new BaseJobServeItem();
            serve.setServeNum(json.getInteger("serveNum"));
            serve.setStoreId(storeId);
            serve.setProjectId(projectManagement.getId());
            serve.setServeId(json.getString("id"));
            baseJobServeItemService.save(serve);
        }

        QueryWrapper<BaseJobShop> queryShop = new QueryWrapper<>();
        queryShop.eq("project_id", projectManagement.getId());
        baseJobShopService.remove(queryShop);
        for (int i = 0; i < jobShop.size(); i++) {
            JSONObject json = jobShop.getJSONObject(i);
            BaseJobShop shop = new BaseJobShop();
            shop.setShopId(json.getString("id"));
            shop.setProjectId(projectManagement.getId());
            shop.setShopNum(json.getInteger("shopNum"));
            shop.setStoreId(storeId);
            baseJobShopService.save(shop);
        }
        return Result.OK("编辑成功！");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目管理-通过id删除")
    @ApiOperation(value = "项目管理-通过id删除", notes = "项目管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        projectManagementService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目管理-批量删除")
    @ApiOperation(value = "项目管理-批量删除", notes = "项目管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.projectManagementService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目管理-通过id查询")
    @ApiOperation(value = "项目管理-通过id查询", notes = "项目管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ProjectManagement projectManagement = projectManagementService.getById(id);
        if (projectManagement == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(projectManagement);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param projectManagement
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ProjectManagement projectManagement) {
        return super.exportXls(request, projectManagement, ProjectManagement.class, "项目管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ProjectManagement.class);
    }

    @AutoLog(value = "商品管理-获取商品编码")
    @ApiOperation(value = "商品管理-获取商品编码", notes = "商品管理-获取商品编码")
    @GetMapping(value = "/getProjectNum")
    public Result<?> getProjectNum(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }

        return Result.OK(getNewCode(storeId));
    }

    private int getNewCode(String storeId) {
        QueryWrapper<ProjectManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.orderByDesc("project_num").last("limit 1");
        ProjectManagement bean = projectManagementService.getOne(queryWrapper);
        if (bean == null || bean.getProjectNum() == null) {
            return 1;
        }
        return bean.getProjectNum() + 1;
    }


}
